<template>
  <div>deepseek前端对接测试</div>
  <div v-html="marked.render(displayText)" class="markdown-body" />
  <div>
    <el-button type="primary" @click="chatMessage">点击测试</el-button>
    <el-button type="primary" @click="handleCopy">点击复制1</el-button>
    <el-button type="primary" @click="handleCopy2">点击复制2</el-button>
  </div>
</template>
<script>
export default {
  name: 'deepSeek'
}
</script>
<script setup>
import {
  copyToClip,
  copyToClip2
} from '@/utils/copy'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'github-markdown-css'
import 'highlight.js/styles/github-dark.css'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
const displayText = ref('')
const marked = new MarkdownIt({
  highlight: (code, lang) => {
    const language = hljs.getLanguage(lang) ? lang : 'shell'
    return `<pre><code class="hljs language-${language}">${hljs.highlight(code, { language }).value}</code></pre>`
  }
})
const chatMessage = async () => {
  const response = await fetch('https://api.deepseek.com/chat/completions',{
    method: 'POST',
    headers: {
      'Authorization': `Bearer sk-fd9c1ccca2a24301af319486a12a3ae0`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'deepseek-chat',
      messages: [{ role: 'user', content: '使用js帮我写一个冒泡排序算法' }],
      temperature: 0.6,
      responseFormat:{type: 'json_object'},
      stream: true // 流式传输需特殊处理
    })
  })
  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let buffer = '';
  while (true) {
    const { done, value } = await reader.read()
    if (done) break


    buffer += decoder.decode(value, { stream: true });// 处理缓冲区中的所有完整消息
    const lines = buffer.split('\n');
    buffer = lines.pop() || ''; // 保留最后一个不完整的行

    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = line.slice(6); // 移除 'data: ' 前缀

        // 跳过心跳消息
        if (data === '[DONE]') continue;

        try {
          const json = JSON.parse(data);
          // 提取并显示实际的消息内容
          if (json.choices && json.choices[0].delta.content) {
            const content = json.choices[0].delta.content;
            displayText.value += content;
          }
        } catch (e) {
          console.error('JSON解析错误:', e);
        }
      }
    }
  }
}

const handleCopy = () => {
  copyToClip(displayText.value).then(() => {
    ElMessage.success('复制成功')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}
const handleCopy2 = () => {
  copyToClip2(displayText.value).then(() => {
    ElMessage.success('复制成功')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}
</script>

<style scoped lang="scss">
.markdown-body {
  width:760px;
  margin:0 auto;
  ::v-deep(pre) {
    background-color: #21252b;
    line-height: 1.6;
    color:#ffffff;
  }
}
</style>